#!/usr/bin/env python3
"""
SchedulerAI Docker Container Test Script

This script tests the Docker container functionality including:
- Container startup
- Health check endpoint
- API functionality
- File upload capability
"""

import json
import os
import sys
import time
import requests
import subprocess
from pathlib import Path

# Configuration
CONTAINER_NAME = "scheduler-ai-test"
IMAGE_NAME = "scheduler-ai:latest"
API_PORT = 8001  # Use different port to avoid conflicts
HEALTH_ENDPOINT = f"http://localhost:{API_PORT}/health"
API_ENDPOINT = f"http://localhost:{API_PORT}/api/v1/optimize"

def run_command(cmd, capture_output=True):
    """Run shell command and return result"""
    try:
        result = subprocess.run(
            cmd, 
            shell=True, 
            capture_output=capture_output, 
            text=True,
            timeout=30
        )
        return result.returncode == 0, result.stdout, result.stderr
    except subprocess.TimeoutExpired:
        return False, "", "Command timed out"

def wait_for_service(url, timeout=60, interval=2):
    """Wait for service to become available"""
    print(f"Waiting for service at {url}...")
    start_time = time.time()
    
    while time.time() - start_time < timeout:
        try:
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                print("✓ Service is ready")
                return True
        except requests.exceptions.RequestException:
            pass
        
        time.sleep(interval)
        print(".", end="", flush=True)
    
    print(f"\n✗ Service not ready after {timeout} seconds")
    return False

def test_health_endpoint():
    """Test health check endpoint"""
    print("\n=== Testing Health Endpoint ===")
    try:
        response = requests.get(HEALTH_ENDPOINT, timeout=10)
        if response.status_code == 200:
            data = response.json()
            print(f"✓ Health check passed")
            print(f"  Status: {data.get('status', 'unknown')}")
            print(f"  Version: {data.get('version', 'unknown')}")
            return True
        else:
            print(f"✗ Health check failed: HTTP {response.status_code}")
            return False
    except Exception as e:
        print(f"✗ Health check error: {e}")
        return False

def test_api_endpoint():
    """Test API endpoint with sample data"""
    print("\n=== Testing API Endpoint ===")
    
    # Create sample CSV data
    sample_csv = """Activity,Duration,Predecessors,Resources
Task1,5,,Worker1
Task2,3,Task1,Worker2
Task3,4,Task1,Worker1
Task4,2,"Task2,Task3",Worker2"""
    
    try:
        # Test with sample CSV data
        files = {'csv_file': ('test.csv', sample_csv, 'text/csv')}
        response = requests.post(API_ENDPOINT, files=files, timeout=30)
        
        if response.status_code == 200:
            data = response.json()
            if data.get('success', False):
                print("✓ API optimization test passed")
                print(f"  Activities processed: {len(data.get('activities', []))}")
                return True
            else:
                print(f"✗ API returned error: {data.get('error_message', 'Unknown error')}")
                return False
        else:
            print(f"✗ API test failed: HTTP {response.status_code}")
            print(f"  Response: {response.text[:200]}...")
            return False
    except Exception as e:
        print(f"✗ API test error: {e}")
        return False

def main():
    """Main test function"""
    print("SchedulerAI Docker Container Test")
    print("=" * 40)
    
    # Check if Docker is available
    success, _, _ = run_command("docker --version")
    if not success:
        print("✗ Docker is not available")
        return False
    
    print("✓ Docker is available")
    
    # Check if image exists
    success, _, _ = run_command(f"docker images -q {IMAGE_NAME}")
    if not success:
        print(f"✗ Docker image {IMAGE_NAME} not found")
        print("Please build the image first using: docker/build.sh")
        return False
    
    print(f"✓ Docker image {IMAGE_NAME} found")
    
    # Stop any existing test container
    run_command(f"docker stop {CONTAINER_NAME}", capture_output=True)
    run_command(f"docker rm {CONTAINER_NAME}", capture_output=True)
    
    # Start container
    print(f"\nStarting container {CONTAINER_NAME}...")
    cmd = f"docker run -d --name {CONTAINER_NAME} -p {API_PORT}:8000 {IMAGE_NAME}"
    success, stdout, stderr = run_command(cmd)
    
    if not success:
        print(f"✗ Failed to start container: {stderr}")
        return False
    
    print(f"✓ Container started: {stdout.strip()}")
    
    try:
        # Wait for service to be ready
        if not wait_for_service(HEALTH_ENDPOINT):
            return False
        
        # Run tests
        tests_passed = 0
        total_tests = 2
        
        if test_health_endpoint():
            tests_passed += 1
        
        if test_api_endpoint():
            tests_passed += 1
        
        # Summary
        print(f"\n=== Test Summary ===")
        print(f"Tests passed: {tests_passed}/{total_tests}")
        
        if tests_passed == total_tests:
            print("✓ All tests passed!")
            return True
        else:
            print("✗ Some tests failed")
            return False
    
    finally:
        # Cleanup
        print(f"\nCleaning up container {CONTAINER_NAME}...")
        run_command(f"docker stop {CONTAINER_NAME}", capture_output=True)
        run_command(f"docker rm {CONTAINER_NAME}", capture_output=True)
        print("✓ Cleanup completed")

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)